package com.amado.course35Concurrent;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018\3\18 0018.
 */
public class S16FetureTestTwo {
	public static void main(String[] args) {
		notUserFuture();
		userFuture();
	}

	public static void notUserFuture() {

		long startTime = new Date().getTime();
		System.out.println("随机数" + (getInt() + getInt()));
		long endTime = new Date().getTime();
		System.out.println("用时" + (endTime - startTime));
	}

	public static void userFuture() {
		long startTime = new Date().getTime();
		try {
			userThraed();
		} catch (ExecutionException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long endTime = new Date().getTime();
		System.out.println("用时" + (endTime - startTime));
	}

	public static String userThraed() throws ExecutionException, InterruptedException {
		ExecutorService executorService = new ThreadPoolExecutor(2, 8, 5, TimeUnit.MINUTES,
				new LinkedBlockingDeque<Runnable>(10),new ThreadPoolExecutor.CallerRunsPolicy());
		// Future future = new FutureTask(new Thraed3(search));
		//返回值用Callable,如果没有返回值的用Runable
		Future<Integer> searchFuture = executorService.submit(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				return getInt();
			}
		});
		//没有返回值
//		executorService.submit(new Runnable() {
//			@Override
//			public void run() {
//			}
//		});
		String abc ="1234";
		Future<String> buyFuture = executorService.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				getInt();
				return "abc";
			}
		});
		//等待计算完成，然后获取其结果。
		Integer searcData = searchFuture.get();
		//等待计算完成，然后获取其结果。
		String buyData = buyFuture.get();
		//销毁线程池
		executorService.shutdown();
		return searcData + buyData;
	}
	/**
	 * 耗时1秒
	 * @return
	 */
	public static int getInt() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Random().nextInt(10);
	}
}
